package com.zzl.alligator.management.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zzl.alligator.common.constant.SystemConstants;
import com.zzl.alligator.common.util.StringUtils;
import com.zzl.alligator.framework.exception.CustomException;
import com.zzl.alligator.framework.support.web.vo.TreeSelect;
import com.zzl.alligator.management.system.domain.SysDept;
import com.zzl.alligator.management.system.domain.SysUser;
import com.zzl.alligator.management.system.mapper.SysDeptMapper;
import com.zzl.alligator.management.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author zhouziliang
 * @since 2020/6/29
 */
@Service
public class SysDeptService implements ISysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> findDeptList(SysDept dept) {
        return sysDeptMapper.selectDeptList(dept);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> resultList = new ArrayList<SysDept>();
        Map<Long, SysDept> map = new HashMap<>();
        depts.forEach(dept -> map.put(dept.getDeptId(), dept));
        depts.forEach(dept -> {
            Long parentId = dept.getParentId();
            if (map.containsKey(parentId)) {
                map.get(parentId).addChild(dept);
            } else {
                resultList.add(dept);
            }
        });
        return resultList;
    }


    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());

    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> findDeptListByRoleId(Long roleId) {
        return sysDeptMapper.selectDeptListByRoleId(roleId);
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept findDeptById(Long deptId) {
        return sysDeptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int findNormalChildrenDeptById(Long deptId) {
        return sysDeptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在部门子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return sysDeptMapper.hasChildByDeptId(deptId) > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return sysDeptMapper.checkDeptExistUser(deptId) > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = sysDeptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return SystemConstants.NOT_UNIQUE;
        }
        return SystemConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDept(SysDept dept) {
        SysDept info = sysDeptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!SystemConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return sysDeptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDept(SysDept dept) {
        SysDept newParentDept = sysDeptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = sysDeptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = sysDeptMapper.updateDept(dept);
        if (SystemConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = sysDeptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        sysDeptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = sysDeptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            sysDeptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDeptById(Long deptId) {
        return sysDeptMapper.deleteDeptById(deptId);
    }

    /**
     * 根据父部门Id 查找部门信息
     *
     * @return 部门列表
     */
    @Override
    @Cacheable(cacheNames = {"COMMON_CACHE"}, key = "#targetClass + '_findDeptListByParentId_' + #p0")
    public List<SysDept> findDeptListByParentId(Long deptId) {
        return sysDeptMapper.selectChildrenDeptByParentId(deptId);
    }

    /**
     * 构建部门用户树
     *
     * @param depts
     * @param users
     * @return
     */
    @Override
    public List<TreeSelect> buildDeptUserTreeSelect(List<SysDept> depts, List<SysUser> users) {
        if (CollectionUtil.isEmpty(depts)) {
            if(users != null) {
                return users.stream().map(TreeSelect::new).collect(Collectors.toList());
            }
            return new ArrayList<>();
        }
        List<TreeSelect> res = new ArrayList<>();
        Map<Long, TreeSelect> map = new HashMap<>();

        depts.forEach(dept -> {
            TreeSelect treeSelect = new TreeSelect();
            treeSelect.setId(dept.getDeptId());
            treeSelect.setNodeId("dept-" + dept.getDeptId());
            treeSelect.setLeaf(false);
            treeSelect.setLabel(dept.getDeptName());
            map.put(dept.getDeptId(), treeSelect);
        });
        for (SysDept dept : depts) {
            if(map.containsKey(dept.getParentId())) {
                map.get(dept.getParentId()).addChild(map.get(dept.getDeptId()));
            } else {
                res.add(map.get(dept.getDeptId()));
            }
        }

        users.forEach(u -> {
            TreeSelect treeSelect = new TreeSelect(u);
            if (map.containsKey(u.getDeptId()) ){

                map.get(u.getDeptId()).addChild(treeSelect);
            }else {
                res.add(treeSelect);
            }
        });
        return res;
    }
}
